package com.baiye.template.utils;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@Component
public class PasswordEncoderUtils implements PasswordEncoder {
    public static String getMd5(String str) {
        byte[] digest = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            digest  = md5.digest(str.getBytes(StandardCharsets.UTF_8));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //16是表示转换为16进制数
        //System.out.println(md5Str);
        return new BigInteger(1, digest).toString(16);
    }

    public static void main(String[] args) {
        String ss=PasswordEncoderUtils.getMd5("admin");
        System.out.println(ss);
        PasswordEncoderUtils password = new PasswordEncoderUtils();
        String sss=password.encode("admin");
        System.out.println(sss);
    }

    @Override
    public String encode(CharSequence charSequence) {
        byte[] digest = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            digest  = md5.digest(charSequence.toString().getBytes(StandardCharsets.UTF_8));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //16是表示转换为16进制数
        //System.out.println(md5Str);
        return new BigInteger(1, digest).toString(16);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return encode(rawPassword).equals(encodedPassword);
    }

}
